import React from 'react';
import {Spin} from 'antd';
import {isEqual, isEmpty} from 'lodash';
import {WeaErrorPage, WeaLocaleProvider, WeaTools, WeaNewScroll} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
const {ls} = WeaTools;
import Title from './Title';
import MarqueeCom from '../common/MarqueeCom';
import FmcsTable from './FmcsTable';
import {setContentviewHeight} from '../../util/common';

//内容组件
class EContent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tabdata: props.edata.data,
            currentTab: props.edata.currenttab,
            refresh: false,
        }
        this.handleTabData = this.handleTabData.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        if (!isEqual(nextProps, this.props)) {
            this.setState({
                tabdata: nextProps.edata.data,
                currentTab: nextProps.edata.currenttab,
                refresh: false,
            });
        }
        this.fixedHead();
    }

    shouldComponentUpdate(nextProps, nextState) {
        return !isEqual(this.state, nextState) || !isEqual(this.props, nextProps)
    }

    componentDidMount() {
        this.props.onRef(this);
        this.fixedHead();
    }

    handleTabData(tabid) {
        this.state.tabdata.data = [];
        this.setState({tabdata: {data: []}});
        const {params, isremembertab} = this.props.config;
        const {currentTab} = this.state;
        this.setState({
            refresh: tabid === currentTab,
            currentTab: tabid,
            tabdata: ls.getJSONObj('tabdata-' + params.eid + '-' + tabid),
        });
        WeaTools.callApi('/api/portal/element/formmodecustomsearchtab', 'POST', {...params, tabid}).then(result => {
            ls.set('tabdata-' + params.eid + '-' + tabid, result);
            let customid = result.customid;
            let morehref = result.morehref;
            if (tabid === this.state.currentTab) {
                this.setState({
                    tabdata: result,
                    refresh: false,
                });
                window.elements_more_params[params.eid] = {isRouteUrl: true, morehref, customid};
                if (isremembertab) {
                    let edata = ls.getJSONObj('edata-' + params.eid);
                    if (edata) {
                        edata.currenttab = tabid;
                        edata.data = result;
                        ls.set('edata-' + params.eid, edata);
                    }
                }
                this.fixedHead();
            }

        });
    }

    fixedHead = () => {
        try {
            const {config} = this.props;
            const {tabdata = {}} = this.state;
            const {tabsetting, data = []} = tabdata;
            if (tabsetting && data.length > 0) {
                if (tabdata['tabsetting'] && tabdata['tabsetting']['rolltype']) {
                    const dir = tabdata.tabsetting.rolltype;
                    if (dir === '1' || dir === '2' || dir === '3' || dir === '4') {
                        const {eid} = config.params;
                        const tabContant = $('#tabcontant_' + eid);
                        const _copyAndHideHeadDOM = () => {
                                const head = tabContant.find('.formmodesearch .ant-table-thead');
                                const fixedHead = head.clone();
                                head.hide();
                                tabContant.prepend(fixedHead);
                            $(`#tabcontant_${eid}>.ant-table-thead`).css({
                                    display: 'table',
                                    tableLayout: 'fixed',
                                    width: tabContant.width()
                                });
                            }
                        const setHead = () => {
                            setTimeout(function(){
                                if ($(`#tabcontant_${eid}>.ant-table-thead`).length > 0) {
                                    $(`#tabcontant_${eid}>.ant-table-thead`).remove();
                                }
                                _copyAndHideHeadDOM();
                            },300)
                        };
                        let counter = 0;
                        const findTable = () => {
                            let timer = setTimeout(function () {
                                counter++;
                                if (tabContant.find('.formmodesearch .ant-table-thead').length > 0 &&
                                    tabContant.find('.formmodesearch .ant-table-tbody tr').length > 0) {
                                    clearTimeout(timer);
                                    setHead();
                                } else {
                                    if (counter <= 40) {
                                        findTable();
                                    } else {
                                        clearTimeout(timer);
                                    }
                                }
                            }, 250)
                        };
                        findTable();
                    }
                }
            }
        } catch (e) {
        }
    };

    render() {
        const {config, edata, handleRefresh, handleDelete, fontSizeMp} = this.props;
        const {tabdata = {}, currentTab, refresh} = this.state;
        if (isEmpty(tabdata)) return <div/>;
        const {tabsetting = {}} = tabdata
        const {tabids, titles, esetting} = edata;
        let {fontStyle, header} = config.item;
        if (!isEmpty(fontSizeMp)) fontStyle = fontSizeMp;
        esetting.fontStyle = fontStyle;
        esetting.widths = tabsetting.widths;
        const {eid} = config.params;
        const {contentview = {}} = config.item;
        let cstyle = {};
        if (header.displayPosition && header.displayPosition == 'bottom' && tabids && tabids.length > 1) {
            if (contentview.style.height) {
                if (esetting.tabstyle == '1' && esetting.tabvalue) {
                    cstyle = setContentviewHeight(contentview.style.height, esetting.tabvalue)
                } else {
                    cstyle = {height: parseInt(contentview.style.height) - 32 + "px", overflow: "auto"};
                }
            } else {
                cstyle = {height: contentview.style.height, overflow: "auto"};
            }
        } else if (tabids && tabids.length == 1) {
            cstyle = {height: contentview.style.height, overflow: "auto"};
        }
        if(header.displayPosition && header.displayPosition == 'bottom') {
            if (tabids && tabids.length > 1 || tabids && tabids.length == 1 && esetting.isAlwaysShow == '1') {
                let elementH=parseInt(contentview.style.height)-parseInt($(`#titleContainer_${eid}`).css('height'))-33;
                if(elementH!=parseInt(cstyle.height)){
                    if(elementH<parseInt(cstyle.height)){
                        cstyle.height=elementH+"px";
                    }
                }
            }
        }
        let rolltype = 'none';
        if (tabdata.tabsetting && tabdata.tabsetting.rolltype == '1') {
            rolltype = 'up';
        } else if (tabdata.tabsetting && tabdata.tabsetting.rolltype == '2') {
            rolltype = 'right';
        } else if (tabdata.tabsetting && tabdata.tabsetting.rolltype == '3') {
            rolltype = 'down';
        } else if (tabdata.tabsetting && tabdata.tabsetting.rolltype == '4') {
            rolltype = 'left';
        }
        let contentHtml = !isEmpty(tabdata) ?
            <MarqueeCom ecId={`${this && this.props && this.props.ecId || ''}_MarqueeCom@fgui15`} eid={eid}
                        scolltype={rolltype}><FmcsTable
                ecId={`${this && this.props && this.props.ecId || ''}_FmcsTable@xax7bj`} currentTab={currentTab}
                eid={eid} isshowtitle={tabdata.tabsetting ? tabdata.tabsetting.isshowtitle : false}
                isPageAutoWrap={tabdata.isPageAutoWrap || '1'} data={tabdata} esetting={esetting}/></MarqueeCom> :
            <div/>;
        const _titleProps = {
            currentTab,
            config,
            titles,
            tabids,
            handleRefresh,
            handleDelete,
            fontSizeMp,
            tabwidth: esetting.tabwidth,
            methodvalue: esetting.methodvalue,
            isAlwaysShow: esetting.isAlwaysShow,
            tabstyle: esetting.tabstyle,
            tabvalue: esetting.tabvalue,
            handleTabData: this.handleTabData
        }
        if (tabdata.secondPassword) {
            return <div>
                <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@2cz7q9`} {..._titleProps}/>
                <div id={`tabcontant_${eid}`} style={{height: cstyle.height, textalign: "center"}}>
                    <WeaNewScroll height={cstyle.height}>
                        <div style={{"textAlign": "center"}}>
                        <span
                            style={{color: "red"}}><i></i>{getLabel(517433, "此查询列表已开启二次身份验证,不支持在门户元素中显示,请联系管理员!")}</span>
                        </div>
                    </WeaNewScroll>
                </div>
            </div>;
        }

        if (tabdata.isdelete) {
            return <div>
                <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@4c95ej`} {..._titleProps}/>
                <div id={`tabcontant_${eid}`}
                     style={{height: cstyle.height, textalign: "center"}}>
                    <WeaNewScroll height={cstyle.height}>
                        <div style={{"textAlign": "center"}}>
                            <span style={{color: "red"}}><i></i>{getLabel(516259, "	所设置的对应查询列表被删除！")}</span>
                        </div>
                    </WeaNewScroll>
                </div>
            </div>;
        }

        return <div>
            <Title ecId={`${this && this.props && this.props.ecId || ''}_Title@h7tgo6`} {..._titleProps}/>
            <div className="tabContant" id={`tabcontant_${eid}`} style={{height: cstyle.height}}>

                <WeaNewScroll height={cstyle.height}>
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@q2zanv`}
                          spinning={refresh}>{contentHtml}</Spin>
                </WeaNewScroll>
            </div>
        </div>;
    }
}

class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return (<WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@t7nw8h`}
                              msg={hasErrorMsg ? this.props.error : getLabel(385218, "对不起，该页面异常，请联系管理员！")}/>
        );
    }
}

EContent = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(EContent);
export default EContent;
